package com.blog.service.impl;


import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.blog.mapper.ArticleMapper;
import com.blog.mapper.CateMapper;
import com.blog.mapper.CommentMapper;
import com.blog.mapper.MemberMapper;
import com.blog.model.Page;
import com.blog.model.ResultJSON;
import com.blog.model.TableJson;
import com.blog.pojo.Article;
import com.blog.pojo.Cate;
import com.blog.pojo.Comment;
import com.blog.pojo.Member;
import com.blog.qiniu.Qiniu;
import com.blog.qiniu.QiniuProperties;
import com.blog.service.ArticleService;
import com.blog.util.FileUtil;
import com.blog.util.JsoupUtil;
import com.blog.util.PageUtil;
import com.blog.util.PictureUtil;

/** 
 * @author ant 
 * @date 创建时间：2017年8月17日 下午2:05:38  
 */
@Service
public class ArticleServiceImpl implements ArticleService {

	@Autowired
	private CateMapper cateMapper;
	
	@Autowired
	private MemberMapper memberMapper;
	
	@Autowired
	private CommentMapper commentMapper;
	
	@Autowired
	private QiniuProperties qiniuProperties;
	
	@Autowired
	private Qiniu qiniu; 
	
	@Autowired
	private ArticleMapper articleMapper;
	
	@Value("${web.upload-path}")
	private String localImagePath;
	
	@Value("${local.path}")
	private String htmlPath;
	
	@Override
	public TableJson getCateList(Cate cate, Page page) {
		TableJson tableJson  = new TableJson();		
		List<Cate> cates = cateMapper.selectByExample(cate,page);
		int total = cateMapper.countByExample(cate);				
		tableJson.setRows(cates);
		tableJson.setTotal(total);
		return tableJson;
	}

	@Override
	public Cate getCateByCateId(Integer cateId) {
		Cate cate = cateMapper.selectByPrimaryKey(cateId);
		return cate;
	}

	@Override
	public ResultJSON editCate(Cate cate, String act) {
		cate.setUpdateTime(new Date());
		ResultJSON json = new ResultJSON();
		if (StringUtils.equalsIgnoreCase("edit", act)) {
			int i = cateMapper.update(cate);
			if (i > 0) {
				json.setSuccess(true);
				json.setMessage("更新成功！");
			} else {
				json.setSuccess(false);
				json.setMessage("更新失败！");
			}
		} else {
			cate.setCreateTime(new Date());
			int i = cateMapper.insert(cate);
			if (i > 0) {
				json.setSuccess(true);
				json.setMessage("创建成功！");
			} else {
				json.setSuccess(false);
				json.setMessage("创建失败！");
			}
		}
		return json;
	}

	@Override
	public ResultJSON addArticle(Article article, List<String> pictureList,MultipartFile thumbnailFile) {
		ResultJSON json = new ResultJSON();
		try {			
			//文件名
			String filename =  FileUtil.getFileName()+".html";
			String htmlUrl = qiniuProperties.getServerPath() + filename;
			article.setArticlePath(htmlUrl);
			List<String> imagePath = new ArrayList<>();
			for (String path : pictureList) {
				if (StringUtils.isNoneBlank(path)) {
					String fileName = path.substring(path.lastIndexOf("/")+1);
					String localPicturePath = localImagePath + path;
					File localFile = new File(localPicturePath);
					if (!localFile.exists()) {
						json.setSuccess(false);
						json.setMessage("内容中的图片不存在，请检查配置。");
						return json;
					}				
					qiniu.uploadFileWithFile(localFile, fileName, qiniuProperties.getBucket());
					localFile.delete();
					String pitureUrl = qiniuProperties.getServerPath() + fileName;
					imagePath.add(pitureUrl);
				}				
			}
			if (thumbnailFile != null) {
				String fileName = thumbnailFile.getOriginalFilename().toLowerCase();
				String type = fileName.substring(fileName.lastIndexOf("."));
				String imgeName = FileUtil.getFileName() + type;
				String thumbnail = qiniuProperties.getServerPath() + imgeName;
				qiniu.uploadFileWithInputStream(thumbnailFile.getInputStream(), imgeName, qiniuProperties.getBucket());
				article.setArticleThumbnail(thumbnail);
			}
			article.setArticleContent(PictureUtil.changeSrc(article.getArticleContent(), imagePath));
			article.setArticleCreateTime(new Date());
			article.setArticleUpdateTime(new Date());
			article.setArticleViewCount(0);
			int i = articleMapper.insert(article);
			if (i > 0) {
				//将html写入到html 文件中
				File file = FileUtil.outputFile( filename, article.getArticleContent(),htmlPath);
				//将该文件上传到服务器上
				boolean result = qiniu.uploadFileWithFile(file, filename, qiniuProperties.getBucket());
				if (result) {
					json.setSuccess(true);
					json.setMessage("添加成功");
				} else {
					json.setSuccess(false);
					json.setMessage("添加失败");				
				}
				file.delete();
			} else {
				json.setSuccess(false);
				json.setMessage("添加失败");
			}
		} catch (Exception e) {
			json.setSuccess(false);
			json.setMessage("添加错误");
			e.printStackTrace();
		}						
		return json;
	}

	@Override
	public List<Cate> listAllCate(Integer cateStatus) {
		List<Cate> cateList = cateMapper.listAllCate(cateStatus);
		return cateList;
	}

	@Override
	public TableJson getArticleList(Article article, Page page) {
		TableJson tableJson  = new TableJson();		
		List<Article> articles = articleMapper.selectByExample(article,page);
		int total = articleMapper.countByExample(article);	
		int totalPage = PageUtil.getTotalPage(total, page.getLimit());		
		tableJson.setTotalPage(totalPage);
		tableJson.setRows(articles);
		tableJson.setTotal(total);
		return tableJson;
	}

	@Override
	public Article getArticleByArticleId(Integer articleId) {
		Article article = articleMapper.selectByPrimaryKey(articleId);
		String articlePath = article.getArticlePath();
		String content = JsoupUtil.parseHtml(articlePath);
		article.setArticleContent(content);
		return article;
	}

	@Override
	public ResultJSON editArticle(Article article, List<String> pictureList, MultipartFile thumbnailFile) {
		ResultJSON json = new ResultJSON();
		try {
			//文件名
			String filename =  FileUtil.getFileName()+".html";
			String htmlUrl = qiniuProperties.getServerPath() + filename;
			article.setArticlePath(htmlUrl);
			List<String> imagePath = new ArrayList<>();
			for (String path : pictureList) {
				if (StringUtils.isNoneBlank(path)) {
					String fileName = path.substring(path.lastIndexOf("/")+1);
					String localPicturePath = localImagePath + path;
					File localFile = new File(localPicturePath);
					if (!localFile.exists()) {
						json.setSuccess(false);
						json.setMessage("内容中的图片不存在，请检查配置。");
						return json;
					}				
					qiniu.uploadFileWithFile(localFile, fileName, qiniuProperties.getBucket());
					localFile.delete();
					String pitureUrl = qiniuProperties.getServerPath() + fileName;
					imagePath.add(pitureUrl);
				}				
			}
			if (thumbnailFile != null) {
				String fileName = thumbnailFile.getOriginalFilename().toLowerCase();
				String type = fileName.substring(fileName.lastIndexOf("."));
				String thumbnail = qiniuProperties.getServerPath() + FileUtil.getFileName() + type;
				qiniu.uploadFileWithInputStream(thumbnailFile.getInputStream(), FileUtil.getFileName() + type, qiniuProperties.getBucket());
				article.setArticleThumbnail(thumbnail);
			}else {
				article.setArticleThumbnail(null);
			}
			
			article.setArticleContent(PictureUtil.changeSrc(article.getArticleContent(), imagePath));
			article.setArticleUpdateTime(new Date());
			int i = articleMapper.update(article);
			if (i > 0) {	
				//将html写入到html 文件中
				File file = FileUtil.outputFile( filename, article.getArticleContent(),htmlPath);	
				//删除html文件
				String htmlPath = article.getArticlePath();
				String htmlName = htmlPath.substring(htmlPath.lastIndexOf("/")+1);
				qiniu.deleteFile(qiniuProperties.getBucket(), htmlName);
				//将该文件上传到服务器上
				qiniu.uploadFileWithFile(file, filename, qiniuProperties.getBucket());
				file.delete();
				json.setSuccess(true);
				json.setMessage("更新成功！");
			} else {
				json.setSuccess(false);
				json.setMessage("更新失败！");
			}
		} catch (Exception e) {
			json.setSuccess(false);
			json.setMessage("更新错误！");
			e.printStackTrace();
		}						
		return json;
	}

	@Override
	public Article getPreviousByPrimaryKey(Integer articleId) {
		Article previousArticle = articleMapper.selectPreviousByPrimaryKey(articleId);
		return previousArticle;
	}

	@Override
	public Article getNextByPrimaryKey(Integer articleId) {
		Article nextArticle = articleMapper.selectNextByPrimaryKey(articleId);
		return nextArticle;
	}

	@Override
	@Transactional(rollbackFor={DataAccessException.class})
	public ResultJSON saveComment(Comment comment) {
		Member member = memberMapper.getMemberByUserName(comment.getMember().getMemberName());
		if (member == null) {
			memberMapper.insert(comment.getMember());
		} 
		int i = commentMapper.insert(comment);
		ResultJSON json = new ResultJSON();
		if (i > 0) {
			json.setSuccess(true);
		} else {
		    json.setSuccess(false);
		    json.setMessage("失败！");
		}
		return json;
	}

	@Override
	public List<Article> selectByViewCount(Integer end) {
		List<Article> articleList = articleMapper.selectByViewCount(end);
		return articleList;
	}

	@Override
	@Transactional(rollbackFor={DataAccessException.class})
	public ResultJSON deleteCate(Integer cateId) {
		List<Article> articleList = articleMapper.selectByCateId(cateId);		
		int i = cateMapper.deleteByPrimaryKey(cateId);
		for (Article article : articleList) {
			this.deleteArticle(article.getArticleId());
		}
		ResultJSON json = new ResultJSON();
		if (i > 0) {
			json.setSuccess(true);
			json.setMessage("删除成功！");
		} else {
			json.setSuccess(false);
			json.setMessage("删除失败！");
		}
		return null;
	}

	@Override
	public ResultJSON deleteArticle(Integer articleId) {
		// TODO Auto-generated method stub
		return null;
	}

}
